<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/6/4 15:56
 */

namespace App\Project\FieldTranslation;

use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;

class FieldTranslation
{
    const BASE_PATH = 'Project/FieldTranslation/';

    /**
     * @var Filesystem
     */
    protected $filesystem;

    /**
     * 已加载的文件容器
     * @var array
     */
    protected $container = [];

    /**
     * 构造器
     * FieldTranslation constructor.
     * @param \Illuminate\Filesystem\Filesystem $filesystem
     */
    public function __construct(Filesystem $filesystem)
    {
        $this->filesystem = $filesystem;
    }

    /**
     * 获取文件内容，支持点获取
     * @param $file
     * @return mixed
     */
    public function get($file)
    {
        $name = $this->parseFileName($file);

        if (!Arr::exists($this->container, $name)) $this->getRequire($name);

        return Arr::get($this->container, $file);
    }

    /**
     * 获取文件名称
     * @param $file
     * @return string
     */
    protected function parseFileName($file)
    {
        if (Str::contains($file, '.')) {

            $elements = explode('.', $file);

            return array_shift($elements);
        }

        return $file;
    }

    /**
     * 加载指定文件
     * @param $file
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
     */
    protected function getRequire($file)
    {
        $this->container[$file] = $this->filesystem->getRequire(
            app_path(self::BASE_PATH . $file . '.php')
        );
    }
}